<?php

/**
 * Class for db import
 *
 * @author Honza
 */
class DBImport {

  public static function import() {
    $isAuthors = false;
    //authors



    $handle = fopen("books_isbn.txt", "r");
    if ($handle) {
      while (($line = fgets($handle)) !== false) {
        $entrys = explode(";", $line);
        $authors = $entrys[1];

        $authorIDs = array();

        foreach (explode(", ", $authors) as $fullname) {
          $author = explode(" ", $fullname, 2);
          $name = $author[0];
          $surname = $author[1];



          $sql = "select * from " . TBL_AUTHORS . " where name='$name' and surname='$surname'";
          $authorResult = DB::sql($sql);
          $authorID = $authorResult[0]['id_author'];

          if ($isAuthors && !$authorResult) {
            //if (not exists) create author
            $sql = "insert into " . TBL_AUTHORS . " values (NULL, '$name', '$surname')";
            $authorID = DB::sql($sql);
            break;
          }

          $authorIDs[] = $authorID;
        }

        //authors are created
        //create book
        $title = trim($entrys[0]);
        $isbn = trim($entrys[3]);
        $imprints = trim($entrys[2]);
        $pages = self::randPages();
        
        
        $sql = 'insert into ' . TBL_BOOKS . " values(0, 2,'$title','$isbn',$pages,'$imprints',1,'Book description')";
        $bookID = DB::sql($sql, 'id_book');

        //authors
        foreach ($authorIDs as $authorID) {
          //create a row in table authors_books
          $sql = 'insert into ' . TBL_AUTHORS_BOOKS . " values($bookID,$authorID)";
          DB::sql($sql);
        }

        //genre
        $genreID = self::randGenre();
        $sql = 'insert into ' . TBL_GENRES_BOOKS . " values($genreID, $bookID)";
        DB::sql($sql);

        //bookprints
        $count = self::randBookPrint();
        $location = self::randLocation();
        
        for ($i = 0; $i < $count; $i++) {
          $sql = 'insert into ' . TBL_BOOK_PRINTS . " values (0, $bookID, $location, CURDATE( ), NULL, 0, NULL)";
          $bookPrintID = DB::sql($sql, 'id_book_print');
          $sql = 'update ' . TBL_BOOK_PRINTS . ' set barcode = ' . $bookPrintID . ' where id_book_print = ' . $bookPrintID;
          DB::sql($sql);
        }
        
      }
    } else {
      // error opening the file.
    }
    fclose($handle);
  }

  private static function randGenre() {
    return rand(1, 8);
  }

  private static function randBookPrint() {
    return rand(1, 5);
  }
  
  private static function randPages() {
    return rand(30, 1000);
  }
  
  private static function randLocation() {
    return rand(2, 3);
  }

}

?>
